package com.polaris.live.adapter.party

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.polaris.live.ui.party.bean.PartySpectatorBean

/**
 * 观众端adapter
 * @author Created by 天晴 on 2024/2/26 17:57
 * @since 1.0.0
 **/
class SpectatorFragmentAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    val data = mutableListOf<PartySpectatorBean>()

    override fun getItemCount(): Int {
        return data.size
    }

    override fun containsItem(itemId: Long): Boolean {
        return data.find { it.fragment.hashCode().toLong() == itemId } != null
    }

    override fun getItemId(position: Int): Long {
        return data[position].fragment.hashCode().toLong()
    }

    override fun createFragment(position: Int): Fragment {
        return data[position].fragment
    }


    fun getDataByIndex(index: Int): PartySpectatorBean? {
        return data.getOrNull(index)
    }

    fun setData(datas: MutableList<PartySpectatorBean>) {
        data.clear()
        data.addAll(datas)
        notifyDataSetChanged()
    }

    /**
     * 设置下一个Fragment  已经有了直接返回有的index
     */
    fun setNextFragment(da: PartySpectatorBean): Int {
        val index = data.indexOfFirst { it.mAnchorId == da.mAnchorId }
        if (index == -1) {
            val newIndex = data.size
            data.add(da)
            notifyItemChanged(newIndex)
            return newIndex
        }
        return index
    }

    /**
     * 添加一个房间
     */
    fun addFragment(da: PartySpectatorBean) {
        val index = data.indexOfFirst { it.mAnchorId == da.mAnchorId }
        if (index == -1) {
            data.add(da)
            notifyItemChanged(data.size - 1)
        }
    }

    fun onDestroy() {
        data.clear()
    }
}